<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商铺编号" prop="resourceId">
        <el-input v-model="queryParams.resourceId" placeholder="请输入商铺编号" clearable @clear="handleQuery"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="使用状态" prop="resourceType">
        <el-select v-model="queryParams.resourceType" placeholder="请选择资源类型" clearable @change="handleQuery">
          <el-option v-for="dict in dict.type.sys_use_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="业主姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入业主姓名" clearable @clear="handleQuery"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:contract:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange" border>
      <el-table-column label="商铺编号" align="center" prop="resourceId" width="88px" />
      <el-table-column label="使用状态" align="center" prop="resourceType" width="88px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_use_type" :value="scope.row.resourceType" />
        </template>
      </el-table-column>
      <el-table-column label="公司名" align="center" prop="company" width="88px" />
      <el-table-column label="业主姓名" align="center" prop="userName" width="88px" />
      <el-table-column label="联系方式" align="center" prop="userPhone" width="120px" />
      <el-table-column label="租金/售价" align="center" prop="money" width="88px" />
      <el-table-column label="行业" align="center" prop="userTrade" width="80px" />
      <el-table-column label="开始使用时间" align="center" prop="beginDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束使用时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" :disabled="scope.row.resourceType !== '3'"
            @click="handleAdd(scope.row)" v-hasPermi="['system:contract:add']">发起合同</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" :disabled="scope.row.resourceType === '3'"
            @click="handleUpdate(scope.row)" v-hasPermi="['system:contract:edit']">编辑合同</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :disabled="scope.row.resourceType === '3'"
            @click="handleDelete(scope.row)" v-hasPermi="['system:contract:remove']">撤销合同</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改租售合同管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body style="margin-top: 100px;">
      <el-steps :active="active" finish-status="success" align-center="center">
        <el-step title="步骤 1" description="确认商铺信息">
          <!-- 步骤 1 的表单项 -->
        </el-step>
        <el-step title="步骤 2" description="选择业主">
          <!-- 步骤 2 的表单项 -->
        </el-step>
        <el-step title="步骤 3" description="设置费用">
          <!-- 步骤 3 的表单项 -->
        </el-step>
      </el-steps>
      <!-- 步骤 1 的表单 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="88px" v-show="active === 0">
        <el-form-item label="商业区" prop="blockName">
          <el-input v-model="blockShop.blockName" disabled />
        </el-form-item>
        <el-form-item label="编号" prop="resourceId">
          <el-input v-model="form.resourceId" disabled />
        </el-form-item>
        <el-form-item label="类型" prop="contractType">
          <el-select v-model="form.contractType" placeholder="请选择类型">
            <el-option v-for="dict in dict.type.sys_contract_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="beginDate">
          <el-date-picker clearable v-model="form.beginDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate" v-if="form.contractType === '0'">
          <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="租金" prop="money" v-if="form.contractType === '0'">
          <el-input v-model="form.money" />
        </el-form-item>
        <el-form-item label="售价" prop="money" v-if="form.contractType === '1'">
          <el-input v-model="form.money" />
        </el-form-item>
      </el-form>
      <!-- 步骤 2 的表单 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="88px" v-show="active === 1">
        <el-form-item label="业主姓名" prop="id" v-if="false">
          <el-input v-model="form.ownerId" />
        </el-form-item>
        <el-form-item label="客户公司" prop="company">
          <el-input v-model="form.company" placeholder="请输入公司名"
            style="display: inline-block; width: 275px; margin-right: 20px;" disabled />
          <el-button type="primary" round @click="handleUser">选择客户信息</el-button>
        </el-form-item>
        <el-form-item label="业主姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入业主姓名" disabled />
        </el-form-item>
        <el-form-item label="身份证" prop="userIdcard">
          <el-input v-model="form.userIdcard" placeholder="请输入业主身份证号" disabled />
        </el-form-item>
        <el-form-item label="手机号" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入手机号" disabled />
        </el-form-item>
        <el-form-item label="性别" prop="userGender">
          <el-select v-model="form.userGender" disabled>
            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="从事行业" prop="userTrade">
          <el-input v-model="form.userTrade" placeholder="请输入从事的行业" />
        </el-form-item>
        <el-form-item label="详细描述" prop="userTradeDetail">
          <el-input v-model="form.userTradeDetail" placeholder="请输入行业的详细描述" />
        </el-form-item>
      </el-form>
      <!-- 步骤 3 的表单 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="88px" v-show="active === 2">
        <el-tabs value="first">
          <el-tab-pane label="设置收费项目" name="first"></el-tab-pane>
        </el-tabs>
        <el-table v-loading="loading" :data="feeOwner.feeList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column label="收费项名" align="center" prop="name" />
          <el-table-column label="单价" align="center" prop="price" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handledelfee(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <el-button style="margin-bottom: 12px; margin-left: 330px;" @click="pre">上一步</el-button>
      <el-button style="margin-bottom: 12px; margin-left: 10px;" @click="next">{{active < 2 ? '下一步' : '确认'}}</el-button>
    </el-dialog>

    <el-dialog title="选择业主" :visible.sync="customerOpen" width="800px" append-to-body>
      <el-form :model="query" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="公司名" prop="company">
          <el-input style="display: inline-block; width: 100px;" v-model="query.company" placeholder="公司名" clearable
            @keyup.enter.native="handleQueryUser" />
        </el-form-item>
        <el-form-item label="业主姓名" prop="name">
          <el-input style="display: inline-block; width: 100px;" v-model="query.name" placeholder="业主姓名" clearable
            @keyup.enter.native="handleQueryUser" />
        </el-form-item>
        <el-form-item label="电话号" prop="phone">
          <el-input style="display: inline-block; width: 120px;" v-model="query.phone" placeholder="联系方式" clearable
            @keyup.enter.native="handleQueryUser" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryUser">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryUser">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="ownerList" @selection-change="handleSelectionChange">
        <el-table-column label="公司名" align="center" prop="company" />
        <el-table-column label="业主姓名" align="center" prop="name" />
        <el-table-column label="身份证号" align="center" prop="idcard" />
        <el-table-column label="手机号码" align="center" prop="phone" />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleSelect(scope.row)">选择业主</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-dialog>


  </div>
</template>

<script>
  import {
    listContract,
    getContract,
    delContract,
    addContract,
    updateContract,
    addPay
  } from "@/api/system/contract";
  import {
    getShops
  } from "@/api/system/shops";
  import {
    listOwner
  } from "@/api/system/owner";
  import {
    listFee_item
  } from "@/api/system/fee_item";

  export default {
    name: "Contract",
    dicts: ['sys_use_type', 'sys_contract_type', 'sys_user_sex'],
    data() {
      return {
        // 业主查询参数
        query: {
          pageNum: 1,
          pageSize: 10,
          company: null,
          name: null,
          phone: null
        },
        // 业主信息对话框
        customerOpen: false,
        //步骤条
        active: 0,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 租售合同管理表格数据
        contractList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          resourceId: null,
          resourceType: null,
          userName: null,
        },
        // 表单参数
        form: {
          beginDate: null,
          endDate: null,
          money: null,
          contractType: null,
        },
        // 表单校验
        rules: {
          resourceId: [{
            required: true,
            message: "商铺编号不能为空",
            trigger: "blur"
          }],
          contractType: [{
            required: true,
            message: "合同类型不能为空",
            trigger: "change"
          }],
          beginDate: [{
            required: true,
            message: "开始时间不能为空",
            trigger: "blur"
          }],
          company: [{
            required: true,
            message: "公司名不能为空",
            trigger: "blur"
          }],
          userName: [{
            required: true,
            message: "业主姓名不能为空",
            trigger: "blur"
          }],
          userIdcard: [{
            required: true,
            message: "业主身份证不能为空",
            trigger: "blur"
          }],
          userPhone: [{
            required: true,
            message: "联系方式不能为空",
            trigger: "blur"
          }],
          userGender: [{
            required: true,
            message: "性别不能为空",
            trigger: "blur"
          }],
          userTrade: [{
            required: true,
            message: "从事的行业不能为空",
            trigger: "blur"
          }],
        },
        // 商业区名称
        blockShop: {
          blockName: null,
        },
        // 业主列表数据
        ownerList: [],
        // 收费列表

        // 收费表
        feeOwner: {
          // 收费项列表
          feeList: [],
          shopId: null,
          ownerId: null,
          startTime: null,
          endTime: null,
          price: null
        },
      };
    },
    created() {
      this.getList();
      this.getfeeList();
    },
    methods: {

      //插入收费表数据
      addPays() {
        this.feeOwner.startTime = this.form.beginDate;
        this.feeOwner.endTime = this.form.endDate;
        this.feeOwner.price = this.form.price;
        if (this.feeOwner.feeList != null) {
          addPay(this.feeOwner);
        }
      },
      //删除收费项
      handledelfee(index, row) {
        this.feeOwner.feeList.splice(index, 1);
      },
      //查询收费项列表
      getfeeList() {
        listFee_item(null).then(resp => {
          this.feeOwner.feeList = resp.rows;
        })
      },
      //选择业主
      handleSelect(row) {
        this.feeOwner.ownerId = row.id;
        this.form.ownerId = row.id;
        this.form.company = row.company;
        this.form.userName = row.name;
        this.form.userIdcard = row.idcard;
        this.form.userPhone = row.phone;
        this.form.userGender = JSON.stringify(row.sex);
        this.customerOpen = false;
        this.open = true;
      },
      // 业主信息对话框
      handleUser() {
        this.open = false;
        this.customerOpen = true;
        this.handleQueryUser();
      },
      // 查询业主列表信息
      handleQueryUser() {
        this.loading = true;
        listOwner(this.query).then(resp => {
          this.ownerList = resp.rows;
          this.total = resp.total;
          this.loading = false;
        })
      },

      //步骤条方法
      pre() {
        if (this.active > 0) {
          this.active--;
        }
      },
      next() {
        if (this.active < 2) {
          this.active++;
        } else {
          this.submitForm();
        }
      },
      /** 查询租售合同管理列表 */
      getList() {
        this.loading = true;
        listContract(this.queryParams).then(response => {
          this.contractList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          money: null,
          blockCode: null,
          resourceId: null,
          resourceName: null,
          resourceType: null,
          ownerId: null,
          contractType: null,
          beginDate: null,
          period: null,
          endDate: null,
          company: null,
          userName: null,
          userIdcard: null,
          userPhone: null,
          userGender: null,
          userTrade: null,
          userTradeDetail: null,
          description: null,
          enabledMark: null,
          creatorUserId: null,
          creatorTime: null,
          lastModifyUserId: null,
          lastModifyTime: null,
          deleteUserId: null,
          deleteTime: null,
        };
        this.feeList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 业主查询表单重置
      resetQueryUser() {
        this.query = {
          pageNum: 1,
          pageSize: 10,
          company: null,
          name: null,
          phone: null
        };
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 发起合同操作 */
      handleAdd(row) {
        this.reset();
        const id = row.id || this.ids
        getContract(id).then(response => {
          response.data.contractType = '1';
          this.form = response.data;
          this.feeOwner.shopId = response.data.resourceId;
          this.open = true;
          this.active = 0;
          this.title = "发起合同";
          //获取商业区名
          getShops(row.resourceId).then(resp => {
            this.blockShop.blockName = resp.data.blockName;
          });
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getContract(id).then(response => {
          this.form = response.data;
          console.log(this.form);
          this.feeOwner.shopId = response.data.resourceId;
          this.open = true;
          this.title = "编辑合同";
        });
        //获取商业区名
        getShops(row.resourceId).then(resp => {
          this.blockShop.blockName = resp.data.blockName;
        });
      },
      handledel(row) {
        handleDelete(row);
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.title == "发起合同") {
              updateContract(this.form).then(response => {
                this.$modal.msgSuccess("发起成功");
                this.open = false;
                this.active = 0;
                this.getList();
                this.addPays();
                this.getfeeList();
              });
            } else {
              updateContract(this.form).then(response => {
                this.$modal.msgSuccess("编辑成功");
                this.open = false;
                this.active = 0;
                this.getList();
                this.addPays();
                this.getfeeList();
              });
            }
          }
        });
      },
      /** 撤销按钮操作 */
      handleDelete(row) {
        const ids = row.id;
        this.$modal.confirm('是否确认撤销租售合同编号为"' + ids + '"的合同？').then(function() {
          return delContract(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("撤销成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/contract/export', {
          ...this.queryParams
        }, `contract_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
